package com.javafactroy.kunlong.bip.icp.message.test.netty.handler.server;


import com.javafactroy.kunlong.bip.icp.message.test.base.TMsg;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import com.javafactroy.kunlong.bip.icp.factory.AppMessageFactory;
import com.javafactroy.kunlong.bip.icp.message.base.iface.IMessage;

@Component
@ChannelHandler.Sharable
@Slf4j
public class TMsgServerHandler extends ChannelInboundHandlerAdapter {
    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) {

        IMessage in = (IMessage) msg;
        log.info("BipServerHandler received: " + in.toString());

        TMsg resp = (TMsg) AppMessageFactory.execute(in);
        resp.getHeader().setMessageId(in.getMessageId());
        ctx.write(resp);
    }

    @Override
    public void channelReadComplete(ChannelHandlerContext ctx) {
        ctx.writeAndFlush(ChannelFutureListener.CLOSE);
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
        cause.printStackTrace();
        ctx.close();
    }

}